package net.sxjr.interceptor;

import lombok.extern.slf4j.Slf4j;
import net.sxjr.common.GlobalParam;
import net.sxjr.common.RedisService;
import net.sxjr.config.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：cuixc
 * @date ：Created in 2020/9/25 13:56
 * @description：登入拦截器
 * @modified By：
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private RedisService redisService;
    public LoginInterceptor(RedisService redisService){
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        boolean b = redisService.hasKey(token);

        if(!b){
            log.error("token 失效 {}",request.getRequestURI());
            throw new RException("token失效",401);
        }
        redisService.expire(token, GlobalParam.tokenTime);
        return true;
    }
}
